<?php

namespace App\V3\V3_2_7\Controllers;

use App\V3\V3_2_7\Models\AdminModel;
use App\V3\V3_2_7\Models\OperationLogModel;
use App\V3\V3_2_7\Models\SystemConfigModel;
use Illuminate\Routing\Controller;
use App\Helper\DBRSAUtil;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Redis;
use Jenssegers\Agent\Agent;

class BaseController extends Controller
{
    private $userId = 0;//子账号
    private $mainUserId = 0;//主账号
    private $userType = 0;//用户类型;0:主账号;1:子账号;
    private $outStorageWay = 0;//是否使用批次号;0:否;1:是;
    private $batchTitle;
    private $isVip;//是否开通vip;0:否;1:是;
    private $isSetAsSupplier;//是否将客户作为供应商使用
    private $isShareCustomer;//是否共享客户;0:否;1:是;
    private $isShareExpress;//是否共享快递信息;0:否;1:是;
    private $isUseShelf;//货架库位使用开关1 使用 0关闭
    private $isShareBreakage;//共享报损：1是 0否
    private $isShareOverflow;//共享报溢：1是 0否
    private $isShareStorage;//共享仓库：1是 0否
    private $isShareStorageOperate;//共享仓库操作：1是 0否
    private $isShareLog;//共享操作记录：1是 0否
    private $isShareReturn;//共享退货:1:是;0:否;
    private $isShareSell;//共享销售1:是;0:否;
    private $isSharePurchase;//共享采购：1是 0否
    private $expressCheckTimes;//快递查询次数
    private $isShareExpressCalc;//	共享快递价格计算：1是 0否
    private $isShareSupplier;//是否共享供应商;0:否;1:是;
    private $subAccountNumber;//可开启子账号数
    private $isSubAdmin = false;//是否为超级管理员

    /**
     * token验证
     * BaseController constructor.
     * @param Request $request
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\excepti on\ModelNotFoundException
     */
    public function __construct(Request $request)
    {
        // token获取
        $token = $request->header('token');
        //$token='4637 rKqkyHorQCdikUl0e3F/Pjbq9VUO0RSxdXIPTtDSTp6J0GVOOuls3ECJU1t7QtjgNx9yMN36Dmfx0/O4aQ5/emdUNTJ4SycKHDhpSNBbC708K2oJW7At/sTQk1k9oI6uufTCSaHIKh8AV5tbPisBnhfd4cjboKvq9JMJRc0HPZc=';
        if (empty($token)) {
            echo json_encode([
                'code' => 2,
                'msg' => 'token获取失败1',
                'data' => '',
            ], JSON_UNESCAPED_UNICODE);
            die;
        }
        $array = explode(' ', $token);

        //私钥获取
        $private = SystemConfigModel::getConfigValue('private');
        if (count($array) < 2) {
            echo json_encode([
                'code' => 2,
                'msg' => 'token参数无效',
                'data' => '',
            ], JSON_UNESCAPED_UNICODE);
            die;
        }

        //解密加密参数并验证
        $rsadata = DBRSAUtil::rsaDecrypt($array[1], $private);
        if ($rsadata == '' || strlen($rsadata) < 50) {
            echo json_encode([
                'code' => 2,
                'msg' => 'token参数无效',
                'data' => '',
            ], JSON_UNESCAPED_UNICODE);
            die;
        }
        $rsadata = json_decode($rsadata, true);
        if ($rsadata == null) {
            echo json_encode([
                'code' => 2,
                'msg' => 'token参数无效',
                'data' => '',
            ], JSON_UNESCAPED_UNICODE);
            die;
        }

        //帐号登陆的时候，会标记这个信息，redis 缓存默认 15天
        /*if(Redis::GET('user_id_'.$rsadata['userId'].'_reset') == 1) {
            echo json_encode([
                'code' => 4,
                'msg' => '权限信息变更，更新使用权限！',
                'data' => '',
            ],JSON_UNESCAPED_UNICODE);die;
        }*/

        if (Redis::GET('user_id_' . $rsadata['userId'] . '_disabled') == 1) {
            echo json_encode([
                'code' => 5,
                'msg' => '当前账号已被禁用，请及时联系主账号',
                'data' => '',
            ], JSON_UNESCAPED_UNICODE);
            die;
        }

        if ($rsadata['userId'] != (int)$array[0]) {
            echo json_encode([
                'code' => 2,
                'msg' => 'token验证失败',
                'data' => '',
            ], JSON_UNESCAPED_UNICODE);
            die;
        } else {
            $userInfo = AdminModel::select(
                'admin.*',
                'is_vip',
                'is_set_as_supplier',
                'is_share_customer',
                'is_share_express',
                'is_use_shelf',
                'is_share_breakage',
                'is_share_overflow',
                'is_share_store',
                'is_share_operating_record',
                'is_share_storage_operate',
                'is_share_sales_return',
                'is_share_sell',
                'is_share_purchase',
                'is_share_billhead',
                'express_check_times',
                'is_share_supplier',
                'is_share_express_price_calculation',
                'sub_account_number',
                'is_use_packages_components',
                'is_open_minute_second',
                'is_share_form',
                'is_share_tally',
                'is_share_shelf_location',
                'is_share_return_barter',
                'is_share_all_info',
                'is_share_product_order',
                'is_use_average_price',
                'is_use_newest_batch_no'
            )
                ->where([
                    'admin.id' => $rsadata['mainUserId'],
                    'parent_id' => 0,
                    'delete_flag' => 0
                ])->leftJoin('admin_addendum as b', 'b.main_id', '=', 'admin.id')->first();

            $mainInfo = AdminModel::where('id', $rsadata['mainUserId'])->first();

            if ($mainInfo['is_sync'] == 0) {
                echo json_encode([
                    'code' => 2,
                    'msg' => 'token已过期，请重新登录1',
                    'data' => '',
                ], JSON_UNESCAPED_UNICODE);
                die;
            }

            $this->userId = $rsadata['userId'];
            $this->mainUserId = $rsadata['mainUserId'];
            $this->userType = $rsadata['userType'];
            $this->outStorageWay = $userInfo['out_storage_way'];
            $this->batchTitle = $userInfo['batch_title'];
            $this->isVip = $userInfo['is_vip'];
            $this->isSetAsSupplier = $userInfo['is_set_as_supplier'];
            $this->isShareCustomer = $userInfo['is_share_customer'];
            $this->isShareExpress = $userInfo['is_share_express'];
            $this->isUseShelf = $userInfo['is_use_shelf'];
            $this->isUseSerial = $userInfo['is_use_serial'];
            $this->isShareBreakage = $userInfo['is_share_breakage'];
            $this->isShareOverflow = $userInfo['is_share_overflow'];
            $this->isShareStorage = $userInfo['is_share_store'];
            $this->isShareStorageOperate = $userInfo['is_share_storage_operate'];
            $this->isShareLog = $userInfo['is_share_operating_record'];
            $this->isShareReturn = $userInfo['is_share_sales_return'];
            $this->isShareSell = $userInfo['is_share_sell'];
            $this->isSharePurchase = $userInfo['is_share_purchase'];
            $this->isShareBillhead = $userInfo['is_share_billhead'];
            $this->expressCheckTimes = $userInfo['express_check_times'];
            $this->isShareExpressCalc = $userInfo['is_share_express_price_calculation'];
            $this->isShareSupplier = $userInfo['is_share_supplier'];
            $this->subAccountNumber = $userInfo['sub_account_number'];
            $this->isShareAllInfo = $userInfo['is_share_all_info'];
            $this->isShareTally = $userInfo['is_share_tally'];
            $this->isShareForm = $userInfo['is_share_form'];
            $this->isOpenMinuteSecond = $userInfo['is_open_minute_second'];
            $this->isUsePackagesComponents = $userInfo['is_use_packages_components'];
            $this->isShareShelfLocation = $userInfo['is_share_shelf_location'];
            $this->isShareReturnBarter = $userInfo['is_share_return_barter'];
            $this->isShareProductOrder = $userInfo['is_share_product_order'];
            $this->isUseAveragePrice = $userInfo['is_use_average_price'];
            $this->isUseNewestBatchNo = $userInfo['is_use_newest_batch_no'];
        }
    }

    /**
     * 是否为超级管理员
     */
    protected function isSubAdmin()
    {
        if (in_array($this->mainUserId, [1])) {
            if ($this->userId == $this->mainUserId) {
                return true;
            }
        }

        return false;
    }

    protected function isUseAveragePrice()
    {
        return $this->isUseAveragePrice;
    }

    protected function isUseNewestBatchNo()
    {
        return $this->isUseNewestBatchNo;
    }

    protected function isShareProductOrder()
    {
        return $this->isShareProductOrder;
    }

    protected function isShareShelfLocation()
    {
        return $this->isShareShelfLocation;
    }

    protected function isShareReturnBarter()
    {
        return $this->isShareReturnBarter;
    }

    protected function isShareAllInfo()
    {
        return $this->isShareAllInfo;
    }

    protected function isShareTally()
    {
        return $this->isShareTally;
    }

    protected function isShareForm()
    {
        return $this->isShareForm;
    }

    protected function isOpenMinuteSecond()
    {
        return $this->isOpenMinuteSecond;
    }

    protected function isUsePackagesComponents()
    {
        return $this->isUsePackagesComponents;
    }

    protected function subAccountNumber()
    {
        return $this->subAccountNumber;
    }

    protected function isShareSupplier()
    {
        return $this->isShareSupplier;
    }

    protected function isShareExpressCalc()
    {
        return $this->isShareExpressCalc;
    }

    protected function expressCheckTimes()
    {
        return $this->expressCheckTimes;
    }

    protected function isShareBillhead()
    {
        return $this->isShareBillhead;
    }

    protected function isSharePurchase()
    {
        return $this->isSharePurchase;
    }

    protected function isShareSell()
    {
        return $this->isShareSell;
    }

    protected function isShareReturn()
    {
        return $this->isShareReturn;
    }

    protected function isShareLog()
    {
        return $this->isShareLog;
    }

    protected function isShareStorage()
    {
        return $this->isShareStorage;
    }

    protected function isShareStorageOperate()
    {
        return $this->isShareStorageOperate;
    }

    protected function isUseSerial()
    {
        return $this->isUseSerial;
    }

    /**
     * 获取当前登录用户id
     * change 在 2021/9/24 14:38 创建
     * @return int|string
     */
    protected function getUserId()
    {
        return $this->userId;
    }

    /**
     *  主账号
     * change 在 2021/10/11 14:47 创建
     * @return int
     */
    protected function getMainUserId()
    {
        return $this->mainUserId;
    }

    /**
     *  账号类型
     * change 在 2021/10/11 14:47 创建
     * @return int
     */
    protected function getUserTpye()
    {
        return $this->userType;
    }

    /**
     * 是否共享快递信息;0:否;1:是;
     * 2022/8/22 18:22
     * Author: Sun Wu
     * @return mixed
     */
    protected function isShareExpress()
    {
        return $this->isShareExpress;
    }

    /**
     * 是否使用批次号;0:否;1:是;
     * AUTHOR  : Sun Wu
     * DateTime: 2022/6/18 14:05
     * @return int|mixed
     */
    protected function getOutWay()
    {
        return $this->outStorageWay;
    }

    protected function batchTitle()
    {
        return $this->batchTitle;
    }

    protected function isVip()
    {
        return $this->isVip;
    }

    protected function isSetAsSupplier()
    {
        return $this->isSetAsSupplier;
    }

    protected function isShareCustomer()
    {
        return $this->isShareCustomer;
    }

    //货架库位使用开关1 使用 0关闭
    protected function isUseShelf()
    {
        return $this->isUseShelf;
    }

    //共享报损：1是 0否
    protected function isShareBreakage()
    {
        return $this->isShareBreakage;
    }

    //共享报溢：1是 0否
    protected function isShareOverflow()
    {
        return $this->isShareOverflow;
    }
    //共享报溢：1是 0否

    /**
     * 成功响应
     * change 在 2021/9/24 14:38 创建
     * @param string $data 响应数据
     * @param string $msg 响应提示
     * @return \Illuminate\Http\JsonResponse
     */
    public function success($data = '', $msg = 'success', $code = 0)
    {
        return response()->json([
            'code' => $code,
            'msg' => $msg,
            'data' => $data,
        ]);
    }

    /**
     * 失败响应
     * change 在 2021/9/24 14:38 创建
     * @param string $data 响应数据
     * @param string $msg 响应提示
     * @return \Illuminate\Http\JsonResponse
     */
    public function fail($data = '', $msg = 'fail', $code = 1)
    {
        return response()->json([
            'code' => $code,
            'msg' => $msg,
            'data' => $data,
        ]);
    }

    /**
     * 操作日志
     * change 在 2021/10/15 13:32 创建
     * @param $remark 操作描述
     * @param $data   操作详细内容
     */
    public function log($remark, $data, $logData = '')
    {
        $res = OperationLogModel::insert([
            'main_id' => $this->getMainUserId(),
            'user_id' => $this->getUserId(),
            'remark' => $remark,
            'data' => json_encode($data, JSON_UNESCAPED_UNICODE),
            'ip' => $_SERVER["REMOTE_ADDR"],
            'created_at' => time(),
            'log_data' => $logData
        ]);
        if (!$res) {
            $this->fail('操作日志插入失败');
        }
    }

    public function operateLog($remark, $data, $time, $logData = '')
    {
        $res = OperationLogModel::insert([
            'main_id' => $this->getMainUserId(),
            'user_id' => $this->getUserId(),
            'remark' => $remark,
            'data' => json_encode($data, JSON_UNESCAPED_UNICODE),
            'ip' => $_SERVER["REMOTE_ADDR"],
            'created_at' => $time,
            'log_data' => $logData
        ]);
        if (!$res) {
            $this->fail('操作日志插入失败');
        }
    }
}
